<template>
  <div>
    <el-drawer
      ref="mtd"
      title="ChatGPT"
      :wrapper-closable="false"
      :visible="dialogVisible"
      size="60%"
      direction="rtl"
      @close="close"
    >
      <el-container>
        <el-header style="height: 35px">
          <el-button size="mini" @click="handleGetAiContent">历史记录</el-button>
        </el-header>
        <el-main style="margin-top: 1px;padding-top:1px">
          <div style="height: 600px" class="auto_scroll">
            <el-card v-for="(item, index) in aicontents" :key="item.id" class="box-card" :title="item.prompt">
              <div slot="header" class="clearfix">
                <span>{{ item.prompt }}</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="handleCopy(item.content)">copy</el-button>
              </div>
              <div class="text item">
                <el-input v-model="item.content" type="textarea" :rows="15" />
              </div>
            </el-card>
          </div>
        </el-main>
        <el-footer>
          <el-row>
            <el-col>
              <el-select
                v-model="template_type"
                size="mini"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="searchPrompts"
                @change="handleInsertTemplate"
              >
                <el-option value="自定义" label="自定义" />
                <el-option v-for="(item, index) in prompttempaltes" :key="item.id" :label="item.name" :value="index" />
              </el-select>
              <el-select v-model="engine" placeholder="选择引擎" size="mini" filterable clearable>
                <el-option label="ChatGPT3.5" value="gpt-3.5-turbo" />
                <el-option label="一般" value="text-davinci-003" />
                <el-option label="普通" value="text-davinci-002" />
              </el-select>
              <el-button
                style="width: 50px"
                size="mini"
                type="warning"
                title="管理prompt"
                icon="el-icon-setting"
                @click="aipromptVisible = true"
              />
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-input v-model="prompt" type="textarea" :rows="8" placeholder="告诉AI写什么" />
              <el-button :loading="loading" type="primary" size="mini" @click="HandleGetContent">立即创建</el-button>
              <el-button :loading="loading" style="float: right" type="success" size="mini" @click="handInsert">插入</el-button>
            </el-col>
          </el-row>
        </el-footer>
      </el-container>
    </el-drawer>
    <aiprompt :is-visible="aipromptVisible" @closeDialog="aipromptVisible=false" />
  </div>
</template>

<script>
import Aiprompt from './aiprompt'
require('vue-select-image/dist/vue-select-image.css')
import Cookies from 'js-cookie'
import { Get as GetAiContent } from '@/api/cms/aicontent'
import { Get as GetAiPrompt } from '@/api/cms/aiprompt'
import qs from 'qs'
import {
  Post
} from '@/api/cms/openai'

export default {
  name: 'Openaidialog',
  components: { Aiprompt },
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    title: {
      type: String,
      default: '###'
    },
    keyword: {
      type: String,
      default: '###'
    },
    visible: {
      type: Boolean,
      default: ''
    }
  },
  data() {
    return {
      aipromptVisible: false,
      activeName: 0,
      aicontents: [],
      template_type: '子标题',
      main_point: '',
      topic: '',
      dialogVisible: false,
      content: '',
      prompt: '',
      prompttempaltes: [],
      engine: 'text-curie-001',
      loading: false,
      pagesize: 20,
      page: 1
    }
  },
  computed: {},
  watch: {
    visible(v) {
      this.dialogVisible = v
      if (v) {
        this.handleGetPrompttempaltes()
        this.scrollToBottom()
        this.handleGetAiContent()
      }
    }
  },
  created() {
    this.engine = Cookies.get('openai-engine') || 'gpt-3.5-turbo'
    this.template_type = Cookies.get('openai-template-type') || '自定义'
  },
  methods: {
    searchPrompts(q) {
      GetAiPrompt(null, qs.stringify({
        all: true,
        kw: q,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.prompttempaltes = response.data.data
        })
    },
    handleGetPrompttempaltes() {
      GetAiPrompt(null, qs.stringify({
        all: true,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.prompttempaltes = response.data.data
        })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        // const div = this.$refs.historyDiv;
        // console.log('div:', div.scrollHeight)
        const drawerBody = document.querySelector('.auto_scroll')
        // console.log(111, drawerBody.scrollHeight)
        drawerBody.scrollTop = drawerBody.scrollHeight
        // div.scrollTo({ top: div.scrollHeight, behavior: 'smooth' });
      })
    },
    handleCopy(content) {
      navigator.clipboard.writeText(content).then(function() {
        this.$message.success('内容已经复制到剪切板')
      }, function() {
        this.$message.error('复制失败')
      })
    },
    handleGetAiContent() {
      GetAiContent(null, qs.stringify({
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.aicontents = response.data.data.reverse()
          this.total = response.data.total
          // this.scrollToBottom()
        })
    },
    handleInsertTemplate(value) {
      if (this.template_type !== '自定义') {
        this.prompt = this.prompttempaltes[this.template_type].prompt
        if (this.title.length) {
          this.prompt = this.prompt.replace(/###/g, this.title).replace(/\[title\]/g, this.title)
        }
        if (this.keyword.length) {
          this.prompt = this.prompt.replace(/\[keyword\]/g, this.keyword)
        }
        // switch (this.template_type) {
        //   case '写段落':
        //     this.prompt = `Write blog sections\nBlog Topic:{topic}\n Blog Section:{section}`
        //     break
        //   case '写标题':
        //     this.prompt = `Write blog title\nBlog Topic:{topic}\n title detail:{topic}`
        //     break
        //   case '子标题':
        //     this.prompt = `Write 5 subtitles of blog topic is: {topic}`
        //     break
        //   case '重写':
        //     this.prompt = `rewrite the text below:\n`
        //     break
        //   case '产品标题':
        //     this.prompt = `Write some product title of:{topic}\n product detail:{detail}`
        //     break
        //   case '产品描述':
        //     this.prompt = `Write a product promote description the product title is:\n`
        //     break
        //   case '自定义':
        //     this.prompt = ''
        //     break
        // }
      } else {
        this.prompt = ''
      }
    },
    HandleGetContent() {
      this.loading = true
      this.content = ''
      Post({ prompt: this.prompt, engine: this.engine })
        .then(response => {
          this.content = response.content
          this.loading = false
          Cookies.set('openai-engine', this.engine)
          Cookies.set('openai-template-type', this.template_type)
          navigator.clipboard.writeText(this.content).then(function() {
            this.$message.success('内容已经复制到剪切板')
          }, function() {
            this.$message.error('复制失败')
          })
          this.handleGetAiContent()
        }).catch(e => {
          console.log('error')
          this.loading = false
        })
    },
    handInsert() {
      this.$emit('successCBK', { content: this.content })
      this.dialogVisible = false
    },
    close() {
      this.$emit('close', false)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
    :deep(.el-upload--picture-card) {
      width: 100%;
    }
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }
  .el-dialog__body {
    margin-top: 5px;
  }
</style>

